/*
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>

typedef enum _BOOL {
	FALSE = 0,
	TRUE = 1
} bool;

int randi(int max)
{
	int rand_num;
	double cof;
	static struct random_data rand_data;
	static char rand_state[256];
	static bool initialized = FALSE;

	if (!initialized) {
		initstate_r((unsigned int)time(NULL), rand_state, sizeof(rand_state), &rand_data);
		initialized = TRUE;
	}
	random_r(&rand_data, &rand_num);
	cof = rand_num / (RAND_MAX + 1.0);
	return (int)(max * cof);
}

/* Subtracts time values to determine run time */
int timeval_subtract (struct timeval *result, struct timeval *t2, struct timeval *t1)
{
  long int diff = (t2->tv_usec + 1000000 * t2->tv_sec) -
    (t1->tv_usec + 1000000 * t1->tv_sec);
  result->tv_sec = diff / 1000000;
  result->tv_usec = diff % 1000000;

  return (diff < 0);
}


/* Starts timer */
void tic (struct timeval *timer) {
    memset(timer,0x0,sizeof(struct timeval));
    gettimeofday (timer, NULL);
    return;
}


/* Stops timer and prints difference to the screen */
void toc (struct timeval *timer) {
  struct timeval tv_end, tv_diff;

  memset(&tv_end,0x0,sizeof(struct timeval));
  memset(&tv_diff,0x0,sizeof(struct timeval));
  gettimeofday (&tv_end, NULL);
  timeval_subtract (&tv_diff, &tv_end, timer);
  fprintf(stderr,"running time is %ld.%06ld\n", tv_diff.tv_sec, tv_diff.tv_usec);
  return;
}

